import { loginUser, registerUser,getQiniuToken,saveFileInfo } from '@/api/user'
export async function checkLoginStatus() {
	console.log("开始检查登录状态")
	const loginStatus = await new Promise((resolve, reject) => {
		uni.checkSession({
			success: () => {
				console.log("登录未失效");
				resolve(true);
			},
			fail: () => {
				console.log("登录失效了");
				resolve(true);
			}
		})
	})
	console.log("登录状态", loginStatus);
	if(!loginStatus) {
		checkShop();
		return;
	}
	
}

export async function login() {
	console.log("开始登录")
	const loginCode = await new Promise((resolve, reject) => {
		uni.login({
			"provider": "weixin",
			// "onlyAuthorize": true, // 微信登录仅请求授权认证
			success: (loginRes) => {
				console.log("code", loginRes.code)
				// 获取临时登录凭证code
				resolve(loginRes.code)
			},
			fail: function(err) {
				// 登录授权失败  
				// err.code是错误码
				console.log("loginError", err)
			}
		})
	})
				
	const res = await loginUser(loginCode);
	if (res.code == 200) {
		// 登录成功
		// 存储token
		uni.setStorageSync('token', res.data.token);
		return true;
		// checkShop();
	} else if (res.code == 0) {
		// 注册
		console.log("执行返回false")
		return false;
	}
}

export async function register(user) {
	
	user.attachmentId = await new Promise((resolve, reject) => {
		// uni.uploadFile({
		// 	url: 'https://www.ym-cloud.cn/wxapi/common/reg-upload-avatar', //仅为示例，非真实的接口地址
		// 	filePath: user.avatarUrl,
		// 	name: 'file',
		// 	success: (uploadFileRes) => {
		// 		console.log(uploadFileRes)
		// 		resolve(JSON.parse(uploadFileRes.data).fileId);
		// 	}
		// });
		getQiniuToken().then((result) => {
		  //获取token
		  let token = result.data;
		          const key = `front_${new Date().getTime()}${Math.floor(
		            Math.random() * 100
		          )}.`+user.avatarUrl.split(".")[1]; //自定义图片名
				  uni.uploadFile({
				  	url: 'https://up-z1.qiniup.com', 
				  	filePath: user.avatarUrl,
				  	name: 'file',
				  	    formData: {
				  	      'token': token,
						  'key':"image/" + key
				  	    },
				  	success: (res) => {
						let params = {
						    fileName: key,
						    saveName: key,
						    fileSize: JSON.parse(res.data).fsize,
						    fileUrl: JSON.parse(res.data).key,
						};
						saveFileInfo(params).then((res) => {
						  resolve(res.data);
						});
				  		//resolve(JSON.parse(uploadFileRes.data).fileId);
				  	}
				  });
		});
	});
	
	user.code = await new Promise((resolve, reject) => {
		uni.login({
			"provider": "weixin",
			// "onlyAuthorize": true, // 微信登录仅请求授权认证
			success: (loginRes) => {
				// 获取临时登录凭证code 
				resolve(loginRes.code)
			},
			fail: function(err) {
				// 登录授权失败  
				// err.code是错误码
			}
		})
	});
	
	const res = await registerUser(user);
	// 注册成功
	// 存储token
	if (res.code == 200) {
		uni.setStorageSync('token', res.data.token);
		uni.showToast({
			title: '注册成功',
			mask: true,
			success: () => {
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}, 1000);
			}
		});
		// checkShop();
	}
}

function checkShop() {
	if (!uni.getStorageSync('shop')) {
		uni.reLaunch({
			url: '/pages/shop/shop'
		})
	}
	 else {
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}
}